<?php

namespace app\api\controller;

use app\admin\app\model\Category;
use app\admin\app\model\Video;
use app\middleware\Auth;
use GuzzleHttp\Client;
use support\Db;
use support\Redis;
use support\Request;

class AutogoController
{

    public function login(Request $request)
    {
        $json = ['code' => 0, 'msg' => '', 'data' => []];
        $card = $request->post('card');
        $serial = $request->post('serial');
        $row = Db::table('card')->where('card', $card)->where('status', 1)->first();

        if (empty($row)) {
            $json['msg'] = '卡密不存在';
        } elseif (strtotime($row->end_time) < time()) {
            $json['msg'] = '卡密已到期';
        } elseif ($row->serial_number && $serial != $row->serial_number) {
            $json['msg'] = '卡密不能重复使用';
        }

        if ($json['msg'] == '') {
            if (empty($row->serial_number)) {
                Db::table('card')->where('id', $row->id)->update([
                    'start_time' => date('Y-m-d H:i:s'),
                    'serial_number' => $serial,
                ]);
            }
            $json['code'] = 1;
            $json['msg'] = 'ok';
            $toke = $request->sessionId();
            Redis::set($toke, $row->id);
            $json['data']['token'] = $toke;
        }

        return json($json);
    }

    public function getTask(Request $request)
    {
        $request->card->task;
        $func = ['foster', 'publish'];
        return call_user_func([$this, $func[$request->card->task]], $request);
    }

    public function foster(Request $request)
    {
        return json(['code' => 1, 'msg' => 'ok', 'data' => array_merge(['type' => 'foster'], $request->card->config)]);
    }

    public function publish(Request $request)
    {
        $video = Video::where([
            ['admin_id', '=', $request->card->admin_id],
            ['category_id', '=', $request->card->category_id],
            ['status', '=', 0],
        ])->inRandomOrder()->first();
//        sk-560cfe79401841b289f6b58479bf1014
        if (empty($video)) {
            return json(['code' => 0, 'msg' => '暂无视频']);
        }
        if ($request->card->config['is_ai_title']) {
            $category = Category::find($video->category_id);
            $title = $category->getAITitle();
            if (!$title['code']) {
                return json(['code' => 0, 'msg' => 'AI标题出错' . $title['title']]);
            }
            $video->title = $title['title'];
        } else {
            $video->title = $request->card->config['title'];
        }
        $video->status = 1;
        $video->save();
        $video->interval_min = $request->card->config['publish_min'];
        $video->interval_max = $request->card->config['publish_max'];
        $video->type = 'publish';
        return json(['code' => 1, 'msg' => 'ok', 'data' => $video]);
    }

    public function finish(Request $request)
    {
        $video_id = $request->post('video_id');
        $video = Db::table('video')->where([
            ['id', '=', $video_id],
            ['admin_id', '=', $request->card->admin_id],
            ['status', '=', 1],
        ])->first();
        if (empty($video)) {
            return json(['code' => 0, 'msg' => '视频不存在']);
        }
        Db::table('video')->where('id', $video_id)->update(['status' => 2]);
        return json(['code' => 1, 'msg' => 'ok']);
    }

    public function getTitle()
    {
        $apiUrl = 'https://api.deepseek.com/v1/chat/completions';
        $apiKey = 'sk-560cfe79401841b289f6b58479bf1014';
        // 构建请求数据
        $requestData = [
            'model' => 'deepseek-chat',
            'messages' => [
                [
                    'role' => 'user',
                    'content' => "请提供一些抖音美女分类的热门标题，按JSON格式返回"
                ]
            ]
        ];

        // 创建 Guzzle 客户端
        $client = new Client();

        try {
            // 发送 POST 请求
            $response = $client->post($apiUrl, [
                'headers' => [
                    'Authorization' => 'Bearer ' . $apiKey,
                    'Content-Type' => 'application/json'
                ],
                'json' => $requestData
            ]);

            // 获取响应内容
            $responseBody = json_decode($response->getBody(), true);
            print_r($responseBody);
            $titles = explode("\n", $responseBody['choices'][0]['message']['content']);
            $rand = array_rand($titles);
            return trim(strstr($titles[$rand], '.'), " \n\r\t\v\0.");
//            return ['code' => 1, 'title' => trim(strrchr($titles[$rand], '.'))];
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
    }
}
